<script setup lang="ts"  name="set_department">
import { defineComponent, onMounted, onActivated , reactive, ref, toRaw } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import type Node from "element-plus/es/components/tree/src/model/node";

import {
  getDeptTree,
  delDept,
  savedept,
  deptUser,
} from "@/api/server_set_department";

interface Tree {
  id: string;
  label: string;
  children?: Tree[];
}

const isEdit = ref(false);
const dialogVisible = ref(false);
const tableInfo = ref({
  id: "",
  label: "",
});
const tableList = ref([]);
const height = ref(0);
const dialogVisible_add = ref(false);
const List = ref<Tree[]>([]);
const page = ref(1);
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const formData = ref({
  name: "",
  phone: "",
  dept_id: "",
  user_id: "",
});
const cascaderProps = reactive({
  label: "label",
  value: "id",
  children: "children",
  checkStrictly: true,
  emitPath: false,
});
const addItem = () => {
  ElMessageBox.prompt("新增一级部门", "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^.{1,100}$/,
    inputErrorMessage: "请输入内容",
  })
    .then(({ value }) => {
      savedept({
        id: 0,
        parentId: 0,
        deptName: value,
      }).then((deptInfo) => {
        const newChild = { id: deptInfo.dept_id, label: value, children: [] };
        List.value.push(newChild);
        getDeptInfo()
      });
    })
    .catch(() => {});
    
};

const handleCurrentChange = (val: number) => {
  getList(val);
};

const getDeptInfo = async () => {
  let res = await getDeptTree();
  if (res.result == "success") {
    List.value = res.deptTree;
    // console.log('列表',res);
    
  }
};
const getList = async (page: number) => {
  let res = await deptUser({
    page: page || 0,
    pageSize: pageSize.value,
    deptId: tableInfo.value.id,
  });
  if (res.result == "success") {
    tableList.value = res.deptUsers || [];
    total.value = Number(res.total || 0);
  }
};
const eidtName = async (node: Node, data: Tree) => {
  ElMessageBox.prompt("编辑部门", "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValue: data.label,
    inputPattern: /^.{1,100}$/,
    inputErrorMessage: "请输入内容",
  })
    .then(({ value }) => {
      data.label = value;
      //用data.id  去更新 后端
      savedept({
        id: data.id,
        deptName: value,
      });
    })
    .catch(() => {});
};
const deptInfo = async (node: Node, data: Tree) => {
  dialogVisible.value = true;
  tableInfo.value = data;
  currentPage.value = 1;
  getList(1);
   // 重新获取数据
   getDeptInfo()
};
const append = async (node: Node, data: Tree) => {
  ElMessageBox.prompt("新增部门", "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^.{1,100}$/,
    inputErrorMessage: "请输入内容",
  })
    .then(async ({ value }) => {
      await savedept({
        id: 0,
        parentId: data.id,
        deptName: value,
      }).then(({ deptInfo }) => {
        //todo savedept 要返回dept_id
        const newChild = { id: deptInfo.dept_id, label: value, children: [] };
        if (!data.children) {
          data.children = [];
          // this.$set(data, 'children', []);
        }
        data.children.push(newChild);
         // 重新获取数据
    getDeptInfo()
      });
    })
    .catch(() => {});
   
};
const remove = (node: Node, data: Tree) => {
  ElMessageBox.confirm(
    `<span>确定要删除 <i style="color:#58B2C5;">${data.label}</i> 吗</span>`,
    "提 示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
      type: "warning",
    }
  ).then(async () => {
    let res = await delDept({
      id: toRaw(data.id),
    });
    if (res.result == "success") {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d: any) => d.id === data.id);
      children.splice(index, 1);
       // 重新获取数据
    getDeptInfo()
    }
  });
};

onMounted(() => {
  let pageTable: any = document.querySelector(".page-table");
  height.value = pageTable.clientHeight;
  console.log(height);
  getDeptInfo();
});
</script>

<template>
  <div class="department-page">
    <div class="page-top">
      <h4>部门配置</h4>
      <el-button type="primary" size="small" @click="addItem"
        >新增部门</el-button
      >
    </div>
    <div class="page-table">
      <el-tree :data="List" node-key="id" :expand-on-click-node="false">
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span
              ><i class="el-icon-edit" @click="() => eidtName(node, data)"></i
            ></span>
            <span class="custom-tree-node-right">
              <el-button link size="small" @click="() => deptInfo(node, data)">
                详情
              </el-button>
              <el-button link size="small" @click="() => append(node, data)">
                新增子部门
              </el-button>
              <el-button link size="small" @click="() => remove(node, data)">
                删除
              </el-button>
            </span>
          </span>
        </template>
      </el-tree>
    </div>

   <el-dialog :close-on-click-modal="false"  :title="tableInfo.label" v-model="dialogVisible" width="360">
      <el-table :data="tableList" min-height="500">
        <el-table-column property="name" label="姓名"></el-table-column>
        <el-table-column property="phone" label="电话"></el-table-column>
      </el-table>
      <el-pagination
        layout="total,prev, pager, next"
        :page-size="pageSize"
        v-model:currentPage="currentPage"
        @current-change="handleCurrentChange"
        :total="total"
      >
      </el-pagination>
    </el-dialog>
  </div>
</template>

<style  lang="scss">
.department-page {
  width: 100%;
  height: 100%;
  .page-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .page-table {
    margin: 16px 0;
    height: calc(100% - 80px);
    .custom-tree-node .el-icon-edit {
      padding: 0 10px;
    }
    .custom-tree-node {
      width: 100%;
      display: flex;
      align-items: center;
    }
    .el-tree-node__content {
      height: 46px;
    }
    .custom-tree-node-right {
      flex: 1;
      text-align: right;
    }
  }
  .page-pagination {
    margin-top: 10px;
  }
}
</style>
